package com.woniuxy.mqproducer.controller;

import com.woniuxy.entity.Student;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * description: SendController <br>
 * date: 2022/1/12 12:19 下午 <br>
 * author: shesaifei <br>
 * version: 1.0 <br>
 */

@RestController
public class SendController {

    @Autowired
    RabbitTemplate rabbitTemplate;

    @GetMapping("/sendemail")
    public String sendEmail() {
        //发送消息
        /**
         * 三个参数：交换机、路由、消息体
         */
        //new CorrelationData(UUID.randomUUID().toString())
        rabbitTemplate.convertAndSend("exchangetopic", "email", "email",
                //设置消息属性
                new MessagePostProcessor() {
                    @Override
                    public Message postProcessMessage(Message message) throws AmqpException {
                        message.getMessageProperties().setExpiration("10000");
                        //设置持久化
                        //message.getMessageProperties().setReceivedDeliveryMode(MessageDeliveryMode.PERSISTENT);
                        message.getMessageProperties().getHeaders().put("h1", "v1");
                        message.getMessageProperties().getHeaders().put("h2", "v2");
                        return message;
                    }
                });
        return "sendemail";
    }

    @GetMapping("/sendesms")
    public String sendSms() {
        rabbitTemplate.convertAndSend("exchangetopic",
                "sms", new Student(1, "zs", new Date()));
        return "sendsms";
    }

    @GetMapping("/sendall")
    public String sendAll() {
        rabbitTemplate.convertAndSend("exchangetopic", "sms.email", "sms.email");
        return "sendall";
    }

    @GetMapping("/sendorder")
    public String sendorder() {
        //发送消息
        System.out.println("订单产生的时间：" + new Date());
        rabbitTemplate.convertAndSend("exchangeorder", "order", new Student(1, "zs", new Date()));
        return "sendorder";
    }

    //发送延迟队列

    @GetMapping("/senddelay")
    public String sendDelay() {
        //发送消息延迟队列
        System.out.println("延迟队列发送时间：" + new Date());
        rabbitTemplate.convertAndSend("exchangedelay", "delay", new Student(1, "zs", new Date())
                , new MessagePostProcessor() {
                    @Override
                    public Message postProcessMessage(Message message) throws AmqpException {
                        //发送到延迟队列的消息也要设置延迟属性
                        message.getMessageProperties().setDelay(10000);
                        return message;
                    }
                });
        return "senddelay";
    }
}
